package com.zxl.always.on.display;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;

import com.zxl.always.on.display.base.BaseActivityLifecycle;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2016/8/30.
 */
public class ActivityLifecycle extends BaseActivityLifecycle {

    private List<Activity> mList;

    private static ActivityLifecycle sInstance;


    private ActivityLifecycle() {
        mList = new ArrayList<>();
    }

    public static void registerActivityLifecycleCallbacks(Application application) {
        if (null == sInstance) {
            sInstance = new ActivityLifecycle();
            application.registerActivityLifecycleCallbacks(sInstance);
        }
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
        super.onActivityCreated(activity, savedInstanceState);
        if (!mList.contains(activity)) {
            mList.add(activity);
        }
    }

    @Override
    public void onActivityDestroyed(Activity activity) {
        super.onActivityDestroyed(activity);
        mList.remove(activity);
    }

    public static Activity getActivity(Class cls) {
        if (null != sInstance) {
            for (Activity activity : sInstance.mList) {
                if (cls == null) {
                    return activity;
                } else if (cls.isInstance(activity)) {
                    return activity;
                }
            }
        }
        return null;
    }
}
